<?php

namespace app\api\controller;

use app\admin\model\Category;
use app\admin\model\Fangjian;
use app\admin\model\Gonggao;
use app\admin\model\Jiameng;
use app\admin\model\Order;
use app\admin\model\Pinglun;
use app\admin\model\Renzheng;
use app\common\controller\Api;
use app\common\service\Wechat;
use fast\Random;
use think\Db;
use think\Config;
use think\Session;

/**
 * 小程序登录
 */
class Login extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * 小程序登录
     *
     * @param string $code code
     * @param string $nickName nickName
     */
    public function loginInfo(Wechat $wechat)
    {
        //        接收前台传来的值
        $code = input('code');
        $nickName = input('nickName');
        $encryptedData = input('encryptedData');
        $iv = input('iv');
        $avatar = input('avatar');

        //        判断是否为空
        if (empty($code) || empty($nickName)) {
//            return json(['code' => 0, 'data' => '', 'mag' => '参数不正确']);
        }
        $phone = '';
        $res = $wechat->login($code);
        if ($iv && $encryptedData) {
            $phone = $wechat->getMobile($res['session_key'], $iv, $encryptedData);
        }
        $arr = [
            'session_key' => $res['session_key'],
            'openid' => $res['openid'],
            'code' => $code,
            'status' => 'normal',
        ];
        if ($phone) {
            $arr['mobile'] = $phone;
        }
        if ($nickName) {
            $arr['nickname'] = $nickName;
            $arr['username'] = $nickName;
        }
        if ($avatar) {
            $arr['avatar'] = $avatar;
        }
        $model = new \app\admin\model\User();
        $user = $model->where('openid', $res['openid'])->find();
        if (!empty($user)) {
            $model->where('openid', $res['openid'])->update($arr);
        } else {
            $model->save($arr);
        }
        $user = $model->where('openid', $res['openid'])->find();
        Session::set("user", $user);

        $token = Random::uuid();
        \app\common\library\Token::set($token, $user['id'], 2592000);
        $user['dy_token'] = $token;


        $this->success('请求成功', $user);
    }

    public function ismobile()
    {
        $this->success('请求成功', [
            'is_bind_mobile' => Config::get('site.is_bind_mobile'),
        ]);
    }

    public function loginByCode(Wechat $wechat)
    {
        $code = input('code');

        $user = $wechat->loginByCode($code);

        $this->success('', $user);
    }
}
